package com.yuanfeng.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

	public class ValidateCodeUtils {

		/**
		 *
		 * 生成验证码
		 */
		static Random ran = new Random();

		public static void main(String[] args) throws Exception {
			FileOutputStream out = new FileOutputStream("e:/code1.png");
			getNewCode(out);

		}

		/**
		 * 写出一张图片到置顶输出流
		 *
		 * @param out
		 */
		public static String getNewCode(OutputStream out) {
			int width = 90;
			int height = 40;
			// 在内存中制作一张图片
			try {
				BufferedImage image = new BufferedImage(width, height,
						BufferedImage.TYPE_INT_BGR);

				// 绘画这张图片
				// 拿到一支画笔
				Graphics g = image.getGraphics();
				// 把底色变成灰色

				g.setColor(Color.GRAY);
				g.fillRect(0, 0, width, height);

				// 写四个随机的中文数字5632
				String number = "";
				for (int i = 1; i <= 4; i++) {
					number += ran.nextInt(10);// 0--9
				}
				// 画笔设置为黑色
				g.setColor(Color.BLACK);
				// 字体
				g.setFont(new Font("黑体", Font.ITALIC, 35));
				// 写字
				g.drawString(number, 20, 30);

				// 写干扰线
				for (int j = 1; j <= 30; j++) {

					int x1 = ran.nextInt(width);
					int x2 = ran.nextInt(width);
					int y1 = ran.nextInt(height);
					int y2 = ran.nextInt(height);
					g.setColor(getRandomColr());
					g.drawLine(x1, y1, x2, y2);

				}
				// 把图片写出到硬盘

				ImageIO.write(image, "png", out);
				return number;
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}

		private static Color getRandomColr() {

			int r = ran.nextInt(256);
			int g = ran.nextInt(256);
			int b = ran.nextInt(256);
			return new Color(r, g, b);
		}

	}
